/**
 * @author banglong
 * @date 2016/10/24
 */
define(['text!../html/components/common/moreSelectDialogTemp.html!strip', 'avalon', 'selectDialogApi',
    'tools', 'Layer', 'Condition', 'Conditions'
  ],
  function (htmlTemp, avalon, api, tools, layer, Condition, Conditions) {

    return function () {
      var runtimeParam;
      var getRuntimeParam = function () {
        return {
          layeroObj: -1,
          sourceData: [],
          timeObj: {}
        };
      };

      var moreSelectVm;
      var getVmOption = function () {
        return {
          $id: 'moreSelect',
          header: [],
          row: [],
          chooseData: [],
          sourceData: [],
          searchValue: '',

          tableComponentsID: ['moreselect_one', 'moreselect_two'],
          operateHtml: '<a href="javascript:;" ms-click="@removeChooseData($index)" slot="buttonText">' +
            '<img src="img/index/u524.png" alt=""><span>删除</span>' +
            '</a>',

          pages: 0, // 总页数
          count: 0, // 综述
          currentPages: 1, // 当前页数

          chooseDataFun: function (data) {
            for (var i = 0; i < moreSelectVm.chooseData.length; i++) {
              if (data[moreSelectVm.row[0]] === moreSelectVm.chooseData[i][moreSelectVm.row[0]]) {
                return;
              }
            }
            moreSelectVm.chooseData.push(data);
          },

          removeChooseDataFun: function (index) {
            moreSelectVm.chooseData.splice(index, 1);
          },

          handleInputSearch: function () {
            tools.throttle(runtimeParam.timeObj, function () {
              getData(runtimeParam, moreSelectVm);
            });
          },

          sureChoose: function () {
            runtimeParam.handleChooseData(moreSelectVm.chooseData.$model);
            layer.close(runtimeParam.layeroObj);
          },

          hideLayer: function () {
            layer.close(runtimeParam.layeroObj);
          },

          fetchPagingData: function (obj, first) {

            if (!first) {
              //得到了当前页，用于向服务端请求对应数据
              runtimeParam.nowPage = obj.curr;
              getData(runtimeParam, moreSelectVm);
            }
          }
        };
      };

      function getData(runtimeParam, moreSelectVm) {
        var loadIndex = layer.load();
        // todo 不适用 只能用在供应商/生产商那里
        var Pycode = new Condition("upper(PyCode)", null, "Like", '%' + moreSelectVm.searchValue.toLocaleUpperCase() + '%', "String");
        var SupplierName = new Condition("SupplierName", null, "Like", '%' + moreSelectVm.searchValue + '%', "String");
        var condition = new Conditions([runtimeParam.condition, new Conditions([Pycode, SupplierName], 'OR')], 'AND');

        api.getData({
          className: runtimeParam.className,
          method: runtimeParam.method,
          condition: JSON.stringify(condition),
          nowPage: runtimeParam.nowPage || 1,
          pageSize: 20
        }).then(function (jsonResult) {

          if (jsonResult.issuccess !== 0) {
            return Promise.reject('获取信息失败');
          }

          var result = JSON.parse(jsonResult.result);
          moreSelectVm.pages = Math.ceil(result.pageCount / result.pageSize);
          moreSelectVm.count = result.pageCount;
          moreSelectVm.currentPages = result.nowPage;

          moreSelectVm.sourceData.splice(0, moreSelectVm.sourceData.length);
          moreSelectVm.sourceData.pushArray(result.pageContent);
          layer.close(loadIndex);

        })['catch'](function (ex) {
          layer.close(loadIndex);
          tools.handleError(ex);
        });
      }

      this.init = function (param) {
        runtimeParam = getRuntimeParam();
        runtimeParam = Object.assign({}, runtimeParam, param);

        runtimeParam.layeroObj = tools.createNewOpenWindow(['800px', '620px'], '多选', htmlTemp,
          false, {
            vmConfig: getVmOption(),
            // 销毁方法
            destroy: function () {
              runtimeParam = null;
              moreSelectVm = null;
            }
          });

        var vmOption = getVmOption();
        // 选中的数据重新加载 进选中的表格中
        vmOption.chooseData = runtimeParam.chooseDataArray.concat();
        vmOption.header = param.header.concat();
        vmOption.row = param.row.concat();
        moreSelectVm = tools.initAvalonVm(avalon, vmOption, '.more-select');

        //获取数据
        getData(runtimeParam, moreSelectVm);
      };
    };
  });